<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];

try {
    // 获取用户基本信息
    $user_balance = getUserBalance($user_id);
    $user_frozen_profit = getUserFrozenProfit($user_id);
    
    // 获取交易统计
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(*) as total_trades,
            SUM(CASE WHEN profit > 0 THEN 1 ELSE 0 END) as win_trades,
            SUM(profit) as total_profit
        FROM transactions 
        WHERE user_id = ?
    ");
    $stmt->execute([$user_id]);
    $trade_stats = $stmt->fetch();
    
    // 计算胜率
    $total_trades = intval($trade_stats['total_trades']);
    $win_trades = intval($trade_stats['win_trades']);
    $win_rate = $total_trades > 0 ? round(($win_trades / $total_trades) * 100, 1) : 0;
    
    // 获取当前持仓数
    $stmt = $pdo->prepare("SELECT COUNT(*) as position_count FROM user_positions WHERE user_id = ? AND is_active = 1");
    $stmt->execute([$user_id]);
    $position_count = $stmt->fetch()['position_count'];
    
    $response = [
        'success' => true,
        'balance' => $user_balance,
        'frozen_profit' => $user_frozen_profit,
        'total_trades' => $total_trades,
        'total_profit' => number_format($trade_stats['total_profit'] ?? 0, 2),
        'win_rate' => $win_rate,
        'current_positions' => $position_count
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '获取账户统计失败: ' . $e->getMessage()
    ]);
}
?>
